package com.tool.frame.model;

import com.tool.util.DbUtil;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import javax.swing.table.AbstractTableModel;

public class MySqlTableModel extends AbstractTableModel
{
  private static final long serialVersionUID = -2736768894984119514L;
  public static final String[] COL_NAMES = { "字段名", "字段类型", "属性名", "属性类型" };

  private String[] attrTypes = null;

  private String ds = null;

  private String sql = null;

  private List list = null;

  public List getList()
  {
    return this.list;
  }

  public void setList(List list)
  {
    this.list = list;
  }

  public MySqlTableModel(String ds, String sql)
  {
    this.ds = ds;
    this.sql = sql;
    executeSql();
  }

  public String getDs()
  {
    return this.ds;
  }

  public void setDs(String ds)
  {
    this.ds = ds;
  }

  public String getSql()
  {
    return this.sql;
  }

  public void setSql(String sql)
  {
    this.sql = sql;
  }

  public String[] getAttrTypes()
  {
    return this.attrTypes;
  }

  public void setAttrTypes(String[] attrTypes)
  {
    this.attrTypes = attrTypes;
  }

  private void executeSql()
  {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try
    {
      conn = DbUtil.getConnection(this.ds);
      stmt = conn.createStatement();
      rs = stmt.executeQuery(this.sql);
      this.list = DbUtil.getColumns(rs);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    finally
    {
      DbUtil.closeJdbc(new ResultSet[] { rs }, new Statement[] { stmt }, new Connection[] { conn });
    }
  }

  public int getColumnCount()
  {
    return COL_NAMES.length;
  }

  public String getColumnName(int column)
  {
    return COL_NAMES[column];
  }

  public int getRowCount()
  {
    return this.list.size();
  }

  public Object getValueAt(int rowIndex, int columnIndex)
  {
    String str = (String)this.list.get(rowIndex);
    String[] tmps = str.split(",");
    return tmps[columnIndex];
  }

  public boolean isCellEditable(int rowIndex, int columnIndex)
  {
    return false;
  }
}